<?php

// +----------------------------------------------------------------------
// | APP设备处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\app;

use app\common\event\Base;
use app\model\ucenter\User as UserModel;
use app\model\app\Device as DeviceModel;
use app\model\app\DeviceUser as DeviceUserModel;
use think\Exception;
use think\facade\Config;
use think\facade\Env;
use think\facade\Lang;
use yicmf\tools\FlowSn;

class Device extends Base
{


    /**
     * 单个推送消息
     * @param array $param
     * @param UserModel $user
     * @param string $from
     * @return array
     */
    public function pushToByClientId($param, $client_id)
    {
//        try {
        $payload = [
            'pages' => '/pages/user/notice',
            'action' => 'page'
        ];
        return $this->pushAndroidByClientId($client_id, '内容1', '内容3', $payload);


        $api = new \GTClient('https://restapi.getui.com', Config::get('api.app_key'), Config::get('api.app_id'), Config::get('api.master_secret'));

        $pushRequest = new \GTPushRequest();
        $gtSet = new \GTSettings();
        $gtStr = new \GTStrategy();
        $gtStr->setDefault(1);
        $gtStr->setXm(4);//"/extra.channel_id" : "130171"
        $gtStr->setMz(4);
        $gtSet->setTtl(720000);
        $gtSet->setStrategy($gtStr);
        $pushRequest->setSettings($gtSet);

        $message = new \GTPushMessage();
        $notify = new \GTNotification();
        // 厂商渠道
        $channel = new \GTPushChannel();
        // 认证通知
        $notify->setTitle('实名认证通过');

        $notify->setBody('尊敬的用户，您的认证信息已经1通过');
        $notify->setChannelId(130171);
        $payload = [
            'pages' => '/pages/user/notification',
            'relation_id' => $param['relation_id'],
            'type' => 'no'
        ];
        $notify->setPayload(json_encode($payload));

        //点击通知后续动作，目前支持以下后续动作:
        //1、intent：打开应用内特定页面url：打开网页地址。2、payload：自定义消息内容启动应用。3、payload_custom：自定义消息内容不启动应用。4、startapp：打开应用首页。5、none：纯通知，无后续动作
        $notify->setClickType('startapp');
        $count = 0;
        $lists = [];

        // 需要重复覆盖消息
        $notify->setNotifyId(time());
        // 唯一id，不可重复，10-32位之间
//					$pushRequest->setRequestId($this->_getMicroTime());
        $pushRequest->setRequestId($this->_getMicroTime() . sprintf("%07d", time()));
        //通知栏
        $message->setNotification($notify);
//         透传
//        $message->setTransmission(json_encode($notify->getApiParam()));

        $ups = new \GTUps();
        $ups->setNotification($notify);
        $ups->addOption('XM', '/extra.channel_id', 130171);
        /**
         * "/message/android/notification/badge/class" : "io.dcloud.PandoraEntry",
         * "/message/android/notification/badge/add_num" : 1,
         * "/message/android/category" : "MARKETING"
         */
        $ups->addOption('HW', '/message/android/notification/badge/class', 'io.dcloud.PandoraEntry');
        $ups->addOption('HW', '/message/android/notification/badge/add_num', 1);
        $ups->addOption('HW', '/message/android/category', 'MARKETING');
        $ups->addOption('HO', '/message/android/notification/badge/class', 'io.dcloud.PandoraEntry');
        $ups->addOption('HO', '/message/android/notification/badge/add_num', 1);
//        $ups->addOption('XM','/extra.channel_id',130171);
//        $data['/extra.channel_id'] = 130171;
//        $ups->setOptions();
        $android = new \GTAndroid();
        $android->setUps($ups);
        $channel->setAndroid($android);
//        $ios = new \GTIos();
//        $channel->setIos($ios);
        $pushRequest->setPushChannel($channel);
        $pushRequest->setPushMessage($message);
        $pushRequest->setCid($client_id);

        //处理返回结果
        $result = $api->pushApi()->pushToSingleByCid($pushRequest);

//        dump($result);

        exit();;
        $lists[] = $result;
        $push = [];
        $push['type'] = 'push';
        $push['request_id'] = $pushRequest->getRequestId();
        $push['notify_id'] = $notify->getNotifyId();
        $push['push_code'] = $result['code'];
        $push['push_msg'] = $result['msg'];
        $push['title'] = $notify->getTitle();
        $push['body'] = $notify->getBody();
        $push['push_time'] = time_format();
        if ($result['code'] == 0) {
            foreach ($result['data'] as $send_no => $datum) {
                $push['send_no'] = $send_no;
                foreach ($datum as $client_id => $item) {
                    $push['push_result'] = $item;
                }
            }
        }

//        dump($push);
        $data['code'] = 0;
        $data['data'] = $count;
        $data['lists'] = $lists;
        $data['time'] = time_format();
        $data['message'] = '操作成功';
//        } catch (Exception $e) {
//            $data['code'] = 1;
//            $data['f'] = $e->getFile();
//            $data['l'] = $e->getLine();
//            $data['message'] = $e->getMessage();
//        }
        return $data;
    }

    /**
     * 单个推送消息
     * @param array $param
     * @param UserModel $user
     * @param string $from
     * @return array
     */
    protected function pushAndroidByClientId($client_id, $title, $body, $payload)
    {
        $api = new \GTClient('https://restapi.getui.com', Config::get('api.app_key'), Config::get('api.app_id'), Config::get('api.master_secret'));
        $pushRequest = new \GTPushRequest();
        $gtSet = new \GTSettings();
        $gtStr = new \GTStrategy();
        $gtStr->setDefault(1);
        $gtStr->setXm(1);//"/extra.channel_id" : "130171"
        $gtStr->setMz(1);
        $gtSet->setTtl(720000);
        $gtSet->setStrategy($gtStr);
        $pushRequest->setSettings($gtSet);
        $message = new \GTPushMessage();
        $notify = new \GTNotification();
        // 厂商渠道
        $channel = new \GTPushChannel();
        // 认证通知
        $notify->setTitle($title);
        $notify->setBody($body);
        $notify->setChannelId(130171);
        $notify->setPayload(json_encode($payload));
        //点击通知后续动作，目前支持以下后续动作:
        //1、intent：打开应用内特定页面url：打开网页地址。2、payload：自定义消息内容启动应用。3、payload_custom：自定义消息内容不启动应用。4、startapp：打开应用首页。5、none：纯通知，无后续动作
        $notify->setClickType('intent');
        $intent = 'intent://io.dcloud.unipush/?#Intent;scheme=unipush;package=com.qifan.yunfuye;launchFlags=0x4000000;component=com.qifan.yunfuye/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=' . $title . ';S.content=' . $body . ';S.payload=' . json_encode($payload) . ';end';
        $notify->setIntent($intent);
        // 重复覆盖消息
        $notify->setNotifyId(time());
        // 唯一id，不可重复，10-32位之间
        $pushRequest->setRequestId(FlowSn::build('P'));
        //通知栏
//        $message->setNotification($notify);
//         透传
        $message->setTransmission(json_encode($notify->getApiParam()));

        $ups = new \GTUps();
        $ups->setNotification($notify);
        $ups->addOption('XM', '/extra.channel_id', 130171);
        /**
         * "/message/android/notification/badge/class" : "io.dcloud.PandoraEntry",
         * "/message/android/notification/badge/add_num" : 1,
         * "/message/android/category" : "MARKETING"
         */
        $ups->addOption('HW', '/message/android/notification/badge/class', 'io.dcloud.PandoraEntry');
        $ups->addOption('HW', '/message/android/notification/badge/add_num', 1);
        $ups->addOption('HW', '/message/android/category', 'MARKETING');
        $ups->addOption('HO', '/message/android/notification/badge/class', 'io.dcloud.PandoraEntry');
        $ups->addOption('HO', '/message/android/notification/badge/add_num', 1);
        $android = new \GTAndroid();
        $android->setUps($ups);
        $channel->setAndroid($android);
//        $ios = new \GTIos();
//        $channel->setIos($ios);
        $pushRequest->setPushChannel($channel);
        $pushRequest->setPushMessage($message);
        $pushRequest->setCid($client_id);

        //处理返回结果
        $result = $api->pushApi()->pushToSingleByCid($pushRequest);

        $push = [];
        $push['type'] = 'push';
        $push['request_id'] = $pushRequest->getRequestId();
        $push['notify_id'] = $notify->getNotifyId();
        $push['push_code'] = $result['code'];
        $push['push_msg'] = $result['msg'];
        $push['title'] = $notify->getTitle();
        $push['body'] = $notify->getBody();
        $push['push_time'] = time_format();
        if ($result['code'] == 0) {
            foreach ($result['data'] as $send_no => $datum) {
                $push['send_no'] = $send_no;
                foreach ($datum as $client_id => $item) {
                    $push['push_result'] = $item;
                }
            }
        }
        return $push;
    }

    /**
     * 单个推送消息
     * @param array $param
     * @param UserModel $user
     * @param string $from
     * @return array
     */
    public function pushToSingleUser($param, $user = null, $from = null)
    {
        try {
            $deviceUser = DeviceUserModel::where('user_id', $user['id'])->where('is_active', 1)->order('update_time DESC')->find();
            if (!$deviceUser || !$deviceUser->device) {
                throw new Exception('暂无设备');
            }
            $device = $deviceUser->device;
            $payload = [];
            switch ($param['type']) {
                case 'rebate_pdd':
                    // 认证通知
                    $payload = [
                        'pages' => '/pages/index/rebate',
                        'action' => 'page'
                    ];
                    break;
                case 'auth':
                    // 认证通知
                    $payload = [
                        'pages' => '/pages/user/manage',
                        'action' => 'page'
                    ];
                    break;
            }

            if ($device['platform'] == 'android') {
                $push = $this->pushAndroidByClientId($device['client_id'], $param['title'], $param['content'], $payload);
            } elseif ($device['platform'] == 'ios') {

            }
            if (!empty($push)) {
                $push['user_id'] = $user['id'];
                $device->pushes()->save($push);
            }
            $data['code'] = 0;
            $data['data'] = 1;
            $data['message'] = '操作成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 单个推送消息
     * @param array $param
     * @param UserModel $user
     * @param string $from
     * @return array
     */
    public function pushToSingleUserTest($param, $user = null, $from = null)
    {
        try {
            $deviceUser = DeviceUserModel::where('user_id', $user['id'])->where('is_active', 1)->order('update_time DESC')->find();
            if (!$deviceUser || !$deviceUser->device) {
                throw new Exception('暂无设备');
            }
            $device = $deviceUser->device;
            $payload = [];
            switch ($param['type']) {
                case 'rebate_pdd':
                    // 认证通知
                    $payload = [
                        'pages' => '/pages/index/rebate',
                        'action' => 'page'
                    ];
                    break;
                case 'auth':
                    // 认证通知
                    $payload = [
                        'pages' => '/pages/user/manage',
                        'action' => 'page'
                    ];
                    break;
            }


            $api = new \GTClient('https://restapi.getui.com', Config::get('api.app_key'), Config::get('api.app_id'), Config::get('api.master_secret'));

            $push = new \GTPushRequest();
            $gtSet = new \GTSettings();
            $gtStr = new \GTStrategy();
//            $gtStr->setDefault(1);
            $gtStr->setIos(4);
            $gtSet->setStrategy($gtStr);
            $push->setSettings($gtSet);
            $push->setRequestId(time());
            $message = new \GTPushMessage();
            $notify = new \GTNotification();
            $notify->setTitle("设置通知标题");
            $notify->setBody("设置通知内容");
            $notify->setPayload(json_encode($payload));
            //点击通知后续动作，目前支持以下后续动作:
            //1、intent：打开应用内特定页面url：打开网页地址。2、payload：自定义消息内容启动应用。3、payload_custom：自定义消息内容不启动应用。4、startapp：打开应用首页。5、none：纯通知，无后续动作
            $notify->setClickType("none");
//            $message->setNotification($notify);
            $message->setTransmission(json_encode($notify->getApiParam()));
//            $message->setTransmission($notify);

            // 厂商渠道
            $channel = new \GTPushChannel();
            $ios = new \GTIos();
            $ios->setType('notify');
            $alert = [
                'title'=>'通知1'.time_format(),
                'body'=>'通知11',
            ];
            $aps = new \GTAps();
            $aps->setAlert($notify);
            $aps->setSound('default');
            $aps->setContentAvailable(0);
            $ios->setAps($aps);
            $ios->setPayload(json_encode($payload));
            $ios->setAutoBadge('+1');

            $channel->setIos($ios);
            $push->setPushChannel($channel);
            $push->setPushMessage($message);
            $push->setCid("c4e8d5726e830940335cd39c627ceeaa");
            //处理返回结果
            $result = $api->pushApi()->pushToSingleByCid($push);
//            dump($channel);
//            dump($push);
            dump($result);

            exit();

            $pushRequest = new \GTPushRequest();
            $gtSet = new \GTSettings();
            $gtStr = new \GTStrategy();
//            $gtStr->setDefault(1);
            $gtStr->setIos(4);
            $gtSet->setStrategy($gtStr);
            $pushRequest->setSettings($gtSet);
            $message = new \GTPushMessage();
            $notify = new \GTNotification();
            // 厂商渠道
            $channel = new \GTPushChannel();
            // 认证通知
            $notify->setTitle('标题111'.time_format());
            $notify->setBody('asdas'.time_format());
            $notify->setPayload(json_encode($payload));
            //点击通知后续动作，目前支持以下后续动作:
            //1、intent：打开应用内特定页面url：打开网页地址。2、payload：自定义消息内容启动应用。3、payload_custom：自定义消息内容不启动应用。4、startapp：打开应用首页。5、none：纯通知，无后续动作
            $notify->setClickType('intent');
            $intent = 'intent://io.dcloud.unipush/?#Intent;scheme=unipush;package=com.qifan.yunfuye;launchFlags=0x4000000;component=com.qifan.yunfuye/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=TITLE1111;S.content=2222222;S.payload=' . json_encode($payload) . ';end';
            $notify->setIntent($intent);
            // 重复覆盖消息
            $notify->setNotifyId(time());
            // 唯一id，不可重复，10-32位之间
            $pushRequest->setRequestId(FlowSn::build('P'));
            //通知栏
        $message->setNotification($notify);
//         透传
//            $message->setTransmission(json_encode($notify->getApiParam()));

            $ups = new \GTUps();
            $ups->setNotification($notify);

            $ios = new \GTIos();
            $channel->setIos($ios);
            $pushRequest->setPushChannel($channel);
            $pushRequest->setPushMessage($message);
            $pushRequest->setCid('c4e8d5726e830940335cd39c627ceeaa');

            //处理返回结果
            $result = $api->pushApi()->pushToSingleByCid($pushRequest);

            $push = [];
            $push['type'] = 'push';
            $push['request_id'] = $pushRequest->getRequestId();
            $push['notify_id'] = $notify->getNotifyId();
            $push['push_code'] = $result['code'];
            $push['push_msg'] = $result['msg'];
            $push['title'] = $notify->getTitle();
            $push['body'] = $notify->getBody();
            $push['push_time'] = time_format();
            dump($result);
            if ($result['code'] == 0) {
                foreach ($result['data'] as $send_no => $datum) {
                    $push['send_no'] = $send_no;
                    foreach ($datum as $client_id => $item) {
                        $push['push_result'] = $item;
                    }
                }
            }
            return $push;


            exit();
            if ($device['platform'] == 'android') {
                $push = $this->pushAndroidByClientId($device['client_id'], $param['title'], $param['content'], $payload);
            } elseif ($device['platform'] == 'ios') {

            }
            if (!empty($push)) {
                $push['user_id'] = $user['id'];
                $device->pushes()->save($push);
            }
            $data['code'] = 0;
            $data['data'] = 1;
            $data['message'] = '操作成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['f'] = $e->getFile();
            $data['l'] = $e->getLine();
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    protected function _toSingle()
    {

    }

    protected function _getMicroTime()
    {
        list($usec, $sec) = explode(" ", microtime());
        $time = ($sec . substr($usec, 2, 3));
        return $time;
    }

    /**
     * 通用更新方法
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function update($param, $user = null)
    {
        try {
            if (empty($param)) {
                throw new Exception(Lang::get('__data_format_error_'));
            }
            $device = DeviceModel::where('client_id', $param['client_id'])->where('app_version_code', $param['app_version_code'])->find();
            if ($device) {
                unset($param['id']);
                if ($param['app_version_code'] != $device['app_version_code']) {
                    // TODO:APP升级日志
                }
                $device->save($param);
            } else { // 新增
                $device = DeviceModel::create($param);
            }
            if ($user) {
                $userDevice = $device->users()->where('user_id', $user['id'])->find();
                if (!$userDevice) {
                    // 新增关联
                    $device->users()->save($user);
                } else {
                    $device->users()->where('user_id', $user['id'])->update(['pivot.is_active' => 1]);
                }
            }
            $data['code'] = 0;
            $data['data'] = $device;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 退出设备
     * @param array $param
     * @param UserModel $user
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    public function logout($param, $user = null)
    {
        try {
            $device = DeviceModel::where('client_id', $param['client_id'])->find();
            if ($device) {
                $userDevice = $device->users()->wherePivot('user_id', $user['id'])->find();
                if ($userDevice) {
                    $device->users()->where('user_id', $user['id'])->update(['pivot.is_active' => 0]);
                }
            }
            $data['code'] = 0;
            $data['message'] = '操作成功';
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


}
